<template>
  <div>
    <!-- 订单列表 -->
    <el-table :data="orders" border stripe style="width: 100%;">
      <el-table-column prop="goodsId" label="商品ID" width="80"></el-table-column>
      <el-table-column prop="description" label="商品描述"></el-table-column>
      <el-table-column label="商品图片">
        <template #default="scope">
          <img :src="scope.row.image" alt="商品图片" style="width: 50px; height: 50px; display:block;">
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" width="60"></el-table-column>
      <el-table-column prop="recipientName" label="收件人姓名"></el-table-column>
      <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
      <el-table-column prop="shippingAddress" label="收货地址"></el-table-column>
      <el-table-column prop="trackingNumber" label="物流单号"></el-table-column>
      <el-table-column prop="logisticsCompany" label="物流公司"></el-table-column>
      <el-table-column prop="shippedAt" label="发货时间">
        <template #default="scope">
          {{ formatDate(scope.row.shippedAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          {{ formatStatus(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button
              v-if="scope.row.status === 1"
              size="small"
              type="success"
              @click="showCompleteConfirmation(scope.row)"
          >
            完成
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination" style="text-align: center; margin-top: 20px;">
      <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="totalItems">
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import request from '@/utils/request.js'; // 确保这是你的axios封装
import { ElMessageBox } from 'element-plus';

const orders = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);

// 加载订单列表
const loadOrders = async (pageNum = 1) => {
  try {
    const res = await request.get('/pointsOrder/page', {
      params: {
        pageNum,
        pageSize: pageSize.value,
        status: '' // 可以根据需要添加默认的状态筛选
      }
    });
    if (res.code === '200') {
      orders.value = res.data.list.map(order => ({
        ...order,
        statusText: order.status.toString()
      })) || [];
      totalItems.value = res.data.total;
    }
  } catch (error) {
    console.error('Failed to load orders:', error);
  }
};

// 处理分页变化
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  loadOrders(newPage);
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化状态
const formatStatus = (status) => {
  switch (status) {
    case 0:
      return '未发货';
    case 1:
      return '已发货';
    case 2:
      return '已完成';
    default:
      return '未知';
  }
};

// 显示完成确认框
const showCompleteConfirmation = (order) => {
  ElMessageBox.confirm(
      '您确定要将此订单标记为已完成吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    completeOrder(order);
  }).catch(() => {
    // 用户取消操作
  });
};

// 完成订单
const completeOrder = async (order) => {
  try {
    const res = await request.put('/pointsOrder/update', {
      id: order.id,
      status: 2 // 已完成
    });
    if (res.code === '200') {
      loadOrders(currentPage.value); // 刷新订单列表
    } else {
      console.error('Failed to update order status:', res.message);
    }
  } catch (error) {
    console.error('Failed to update order status:', error);
  }
};

// 初始化加载订单列表
onMounted(() => {
  console.log('Component mounted, loading orders...');
  loadOrders();
});
</script>

<style scoped>
.pagination {
  text-align: center;
  margin-top: 20px;
}
</style>
